package com.hj.system.config.security.jwt;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hj.system.config.security.base.UserInfo;
import com.hj.system.entity.base.UserEntity;
import com.hj.system.entity.base.UserRoleEntity;
import com.hj.system.mapper.UserMapper;
import com.hj.system.mapper.UserRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义处理类 查询用户
 */
@Component
public class JwtUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    private Logger logger = LoggerFactory.getLogger(com.hj.system.config.security.base.MyUserDetailsService.class);
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isNotBlank(username)) {
            QueryWrapper wrapper = new QueryWrapper<UserEntity>();
            wrapper.eq("user_name", username);
            List<UserEntity> userEntityList = userMapper.selectList(wrapper);
            if (userEntityList.size() > 0) {
                UserEntity userEntity = userEntityList.get(0);
                int userId = userEntity.getUserId();
                List<UserRoleEntity> userRoleEntities = userRoleMapper.selectList(new QueryWrapper<UserRoleEntity>() {
                }.eq("user_id", userId));
                List<String> roleIds = userRoleEntities.stream().map(m -> String.valueOf(m.getRoleId())).collect(Collectors.toList());
                UserInfo userInfo = new UserInfo(String.valueOf(userId), userEntity.getUserName(), userEntity.getPassword(), true, true, true, true);
                userInfo.setRoles(roleIds);
                return userInfo;
            }
        }
        return null;
    }
}
